import { history } from 'umi';
import arouter from '@/utils/apulis-router';
import React, { useState, useRef, useEffect, forwardRef, useMemo } from 'react';
import { PageContainer, FooterToolbar, PageHeader } from '@ant-design/pro-layout';
import { ConsoleSqlOutlined, InboxOutlined } from '@ant-design/icons';
import {
  Button,
  message,
  Input,
  Radio,
  Checkbox,
  Card,
  Upload,
  Steps,
  Form,
} from 'antd';
import './index.less';
import style from './index.less';

import * as tus from 'tus-js-client';

import Uppy from '@uppy/core';
import { Dashboard } from '@uppy/react';
import '@uppy/dashboard/dist/style.css';
import Tus from '@uppy/tus';
import Chinese from '@uppy/locales/lib/zh_CN';

import { getPvc, deleteFile } from './service.js';

const { Dragger } = Upload;
import { uploadModel, tets } from './service';
import { FILE_SERVER_URL } from '@/services/common.js';
import { func } from 'prop-types';
// import { await } from '@umijs/deps/compiled/signale';
//import { useMemo } from '@umijs/renderer-react/node_modules/@types/react';
const {Step} = Steps;

const modelUpload = (props, ref) => {
  const [uploadForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [percent, setPercent] = useState(0);
  const [filePath, setFilePath] = useState('');
  const [step, setStep] = useState(0);

  //选项组
  const [preSet, setPreSet] = useState(true);
  const [support, setSupport] = useState(['trainSupport','inferSupport']);
  const options = [{label:'是',value:true},{label:'否',value:false}];
  const supportOptions = [{label:'支持训练',value:'trainSupport',defaultChecked:true},{label:'支持推理',value:'inferSupport',defaultChecked:true}];

  //模板下载地址
  const sampleUrl = '/file/demo_model.zip';

  useEffect(() => {
    tets().then((res) => console.log);
  }, []);

  const onFinish = () => {
    setLoading(true);
    let v = uploadForm.getFieldsValue(true); // 获取表单所有值
    let info = {
      scope: v.scope,
      modelDescription: v.modelDescription,
      filePath: v.filePath,
      fileName: v.fileName,
      modelName: v.modelName,
    };

    uploadModel(info).then((res) => {
      if (res.code === 0) {
        history.push('/models');
      } else {
        message.error(res.msg);
      }
      setLoading(false);
    });
  };

  const uppy = useMemo(() =>{
    const options = {
      meta:{
        location: '',
        moduleName: 'apworkshop',
      },
      restrictions:{
        maxNumberOfFiles: 1,
        allowedFileTypes:['.zip'],
      },
      locale: Chinese,
    }
    return new Uppy(options).use(Tus,{
      formData: true,
      fieldName:'file',
      endpoint:FILE_SERVER_URL,
      retryDelays: [0, 3000, 5000, 10000, 20000],
      headers: {
        Location: 2400,
      },
      chunkSize: 4 * 1024 *1024,
    }).on('complete', async(result) => {
      const uploadURL = result.successful[0].uploadURL;
      const uploadFileName = result.successful[0].name;
      const fileId = uploadURL.split('/').pop() || '';
      const {code,data} = (await getPvc(fileId)) || {};
      if(code === 0){
        const {storagePath} = data;
        setFilePath(storagePath);
        uploadForm.setFieldsValue({
          filePath: storagePath,
          fileName: uploadFileName,
        });
      }
    }).on('file-removed', async(file) =>{
      if(file.uploadURL){
        const fileId = file.uploadURL.split('/').pop() || '';
        const {code, data} = (await deleteFile(fileId) || {});
        setFilePath('');
        uploadForm.setFieldsValue({
          filePath: '',
          fileName: '',
        });
      }
    }).on('cancel-all', async() =>{
    })
  }, []);

  const uppyProps = {
    note : '支持扩展名：.zip .tar'
  };

  //进度条控制
  function nextStep(){
    switch(step){
      case 0:
        //上传文件阶段，校验yaml文件
        break;
      case 1:
        //训练设置阶段
        break;
    }
    setStep(step + 1);
  }

  function previousStep(){
    setStep(step - 1);
  }

  //退出模型上传，回到模型库页面
  function cancel(){
    arouter({ name: 'modelIndex'});
  }

  //副标题
  const subtitle = (title) => {
    return (
      <div className={style.subtitle}>
        <div className={style.subtitleIcon} />
        <h3>{title}</h3>
      </div>
    );
  };

  return (
    <div>
      <PageContainer
        onBack={() => {
          history.push('/models');
        }}
        title="模型详情"
      >
        <Card>
          {/* <Steps current={step} className={style.stepWrapper}>
            <Step title="上传文件"></Step>
            <Step title="训练设置"></Step>
            <Step title="推理设置"></Step>
          </Steps> */}

          <Form
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ modelDescription: '', scope: 'preset' }}
            onFinish={onFinish}
            form={uploadForm}
          >
            <Form.Item
              label="模型名称"
              name="modelName"
              rules={[{ required: true, message: '请输入模型名称，限制在100字符内' }]}
            >
              <Input maxLength={100}/>
            </Form.Item>

            <Form.Item label="模型描述" name="modelDescription" rules={[{required: false}]}>
              <Input.TextArea maxLength={140} showCount defaultValue='请输入描述，限制 140 字符以内'/>
            </Form.Item>

            <Form.Item
              label="模型上传"
              name="filePath"
              tooltip="支持扩展名：.zip"
              rules={[{required: true,message:'请上传模型'}]}>
                {/* <div style={{display: 'flex'}}>
                  <div style={{flex:2}}> */}
                    <Dashboard
                      width="100%"
                      height="100%"
                      uppy={uppy}
                      {...uppyProps}
                      locale={{
                        strings:{
                          browse: '上传',
                          youCanOnlyUploadFileTypes:'只支持上传格式为.zip .tar的文件',
                          done:'重置',
                        }
                      }}
                    />
                  {/* </div>
                  <div style={{marginLeft: '36px',display:'flex', alignItems:'center'}}>
                    <a href={sampleUrl}>
                      <Button type="primary">下载模型示例</Button>
                    </a>
                  </div>
                </div> */}
            </Form.Item>

            {/* <Form.Item label="是否设为预置模型" name="preSet" rules={[{required: true}]}>
              <Radio.Group onChange={e => setPreSet(e.target.value)} options={options}  value={preSet} defaultValue={options[0].value}>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="支持任务" name="support" rules={[{required: true}]}>
              <Checkbox.Group onChange={e => setSupport(e)} options={supportOptions} defaultValue={['trainSupport']}>
              </Checkbox.Group>
            </Form.Item> */}

            <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
              <Button className={style.buttonWrapper} type="primary" htmlType="submit" loading={loading} disabled={filePath?false:true}>
                提交
              </Button>
              {/* <Button onClick={cancel} className={style.buttonWrapper}>
                取消
              </Button>
              { step > 0 && <Button  className={style.buttonWrapper} type="primary" onClick={previousStep}>
                上一步
              </Button>}
              { step < 2 && <Button  className={style.buttonWrapper} type="primary" onClick={nextStep}>
                下一步
              </Button>}
              { step === 2 && <Button  className={style.buttonWrapper} type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>} */}
            </Form.Item>
          </Form>
        </Card>
      </PageContainer>
    </div>
  );
};

export default modelUpload;
